// eslint-disable-next-line no-unused-vars
const Vue = require('vue')
const express = require('express')
const app = express()
const fs = require('fs')
const path = require('path')

// 创建渲染器
const { createBundleRenderer } = require('vue-server-renderer')
const serverBundle = require('../dist/server/vue-ssr-server-bundle.json')

const clientManifest = require('../dist/client/vue-ssr-client-manifest.json')
const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false,
  template: fs.readFileSync('../public/index.temp.html', 'utf-8'), // 宿主模板文件
  clientManifest
})

// 中间件处理静态文件请求
app.use(express.static(path.resolve(__dirname, '../dist/client'), { index: false }))

// 路由处理交给vue
app.get('*', async (req, res) => {
  try {
    const context = {
      url: req.url,
      title: 'ssr test'
    }
    // 将vue实例转为html
    const html = await renderer.renderToString(context)
    // console.log(html)
    res.send(html)
  } catch (e) {
    res.send('服务端异常')
  }
})

app.listen(8000, () => {
  console.log('listen 8000')
})
